package com.muyu.cloud.commodity.service.imp;

import com.muyu.cloud.commodity.domain.model.Product;
import com.muyu.cloud.commodity.domain.model.ProductSku;
import com.muyu.cloud.commodity.domain.model.Brand;
import com.muyu.cloud.commodity.domain.model.Category;
import com.muyu.cloud.commodity.domain.model.SpecGroup;
import com.muyu.cloud.commodity.mapper.ProductMapper;
import com.muyu.cloud.commodity.mapper.ProductSkuMapper;
import com.muyu.cloud.commodity.mapper.BrandMapper;
import com.muyu.cloud.commodity.mapper.CategoryMapper;
import com.muyu.cloud.commodity.mapper.SpecGroupMapper;
import com.muyu.cloud.commodity.service.ProductRemoteService;
import com.muyu.common.core.domain.Result;
import com.muyu.common.product.domain.StockCheckReq;
import com.muyu.common.product.domain.StockCheckResp;
import com.muyu.common.product.domain.ProductInfo;
import com.muyu.common.product.domain.ProductSkuInfo;
import com.muyu.common.product.domain.BrandInfo;
import com.muyu.common.product.domain.CategoryInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 商品服务远程调用服务实现类
 *
 * @author JiaCheng
 * @version 1.0
 * @since 2025-09-21
 */
@Service
public class ProductRemoteServiceImpl implements ProductRemoteService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Override
    public Result<Product> getProductInfo(Long productId) {
        try {
            Product product = productMapper.selectById(productId);
            if (product == null) {
                return Result.error("商品不存在");
            }
            return Result.success(product);
        } catch (Exception e) {
            return Result.error("获取商品信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result<ProductSku> getSkuInfo(Long skuId) {
        try {
            ProductSku sku = productSkuMapper.selectById(skuId);
            if (sku == null) {
                return Result.error("SKU不存在");
            }
            return Result.success(sku);
        } catch (Exception e) {
            return Result.error("获取SKU信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Brand> getBrandInfo(Long brandId) {
        try {
            Brand brand = brandMapper.selectById(brandId);
            if (brand == null) {
                return Result.error("品牌不存在");
            }
            return Result.success(brand);
        } catch (Exception e) {
            return Result.error("获取品牌信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Category> getCategoryInfo(Long categoryId) {
        try {
            Category category = categoryMapper.selectById(categoryId);
            if (category == null) {
                return Result.error("分类不存在");
            }
            return Result.success(category);
        } catch (Exception e) {
            return Result.error("获取分类信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Product>> getBatchProductInfo(List<Long> productIds) {
        try {
            if (productIds == null || productIds.isEmpty()) {
                return Result.success(List.of());
            }
            List<Product> productList = productMapper.selectBatchIds(productIds);
            return Result.success(productList);
        } catch (Exception e) {
            return Result.error("批量获取商品信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<ProductSku>> getBatchSkuInfo(List<Long> skuIds) {
        try {
            if (skuIds == null || skuIds.isEmpty()) {
                return Result.success(List.of());
            }
            List<ProductSku> skuList = productSkuMapper.selectBatchIds(skuIds);
            return Result.success(skuList);
        } catch (Exception e) {
            return Result.error("批量获取SKU信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result<StockCheckResp> checkStock(StockCheckReq stockCheckReq) {
        try {
            ProductSku sku = productSkuMapper.selectById(stockCheckReq.getSkuId());
            if (sku == null) {
                return Result.error("SKU不存在");
            }
            
            Integer currentStock = sku.getStock();
            Integer checkQuantity = stockCheckReq.getQuantity();
            boolean sufficient = currentStock >= checkQuantity;
            
            StockCheckResp resp = StockCheckResp.builder()
                    .skuId(stockCheckReq.getSkuId())
                    .sufficient(sufficient)
                    .currentStock(currentStock)
                    .checkQuantity(checkQuantity)
                    .stockStatus(sufficient ? 0 : (currentStock > 0 ? 1 : 2))
                    .stockStatusText(sufficient ? "库存充足" : (currentStock > 0 ? "库存不足" : "无库存"))
                    .build();
            
            return Result.success(resp);
        } catch (Exception e) {
            return Result.error("检查库存失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<SpecGroup>> getProductSpecs(Long productId) {
        try {
            List<SpecGroup> specGroups = specGroupMapper.selectByProductId(productId);
            return Result.success(specGroups);
        } catch (Exception e) {
            return Result.error("获取商品规格信息失败: " + e.getMessage());
        }
    }

    /**
     * 将Product实体转换为ProductInfo DTO
     */
    public ProductInfo convertToProductInfo(Product product) {
        if (product == null) {
            return null;
        }
        return ProductInfo.builder()
                .productId(product.getId())
                .productName(product.getProductName())
                .description(product.getDescription())
                .thumbnail(product.getProductPic()) // 手动映射 productPic -> thumbnail
                .mainImage(product.getProductPic()) // 主图也使用 productPic
                .status(product.getStatus())
                .brandId(product.getBrandId())
                .categoryId(product.getCategoryId())
                .createTime(convertToLocalDateTime(product.getCreatedAt()))
                .updateTime(convertToLocalDateTime(product.getUpdatedAt()))
                .build();
    }

    /**
     * 将ProductSku实体转换为ProductSkuInfo DTO
     */
    public ProductSkuInfo convertToProductSkuInfo(ProductSku sku) {
        if (sku == null) {
            return null;
        }
        return ProductSkuInfo.builder()
                .skuId(sku.getId())
                .productId(sku.getProductId())
                .skuCode(sku.getSkuCode())
                .specs(sku.getSpecs())
                .price(sku.getSalePrice())
                .originalPrice(sku.getCostPrice())
                .stock(sku.getStock())
                .image(sku.getImage())
                .createTime(sku.getCreatedAt())
                .updateTime(sku.getUpdatedAt())
                .build();
    }

    /**
     * 将Brand实体转换为BrandInfo DTO
     */
    public BrandInfo convertToBrandInfo(Brand brand) {
        if (brand == null) {
            return null;
        }
        BrandInfo brandInfo = new BrandInfo();
        brandInfo.setBrandId(brand.getId());
        brandInfo.setBrandName(brand.getBrandName());
        brandInfo.setLogo(brand.getBrandLogo());
        brandInfo.setDescription(brand.getDescription());
        brandInfo.setStatus(brand.getStatus());
        brandInfo.setCreateTime(convertToLocalDateTime(brand.getCreatedAt()));
        brandInfo.setUpdateTime(convertToLocalDateTime(brand.getUpdatedAt()));
        return brandInfo;
    }

    /**
     * 将Category实体转换为CategoryInfo DTO
     */
    public CategoryInfo convertToCategoryInfo(Category category) {
        if (category == null) {
            return null;
        }
        CategoryInfo categoryInfo = new CategoryInfo();
        categoryInfo.setCategoryId(category.getId());
        categoryInfo.setCategoryName(category.getCategoryName());
        categoryInfo.setParentId(category.getParentId());
        categoryInfo.setLevel(category.getLevel());
        categoryInfo.setSort(category.getSort());
        categoryInfo.setStatus(category.getStatus());
        categoryInfo.setCreateTime(convertToLocalDateTime(category.getCreatedAt()));
        categoryInfo.setUpdateTime(convertToLocalDateTime(category.getUpdatedAt()));
        return categoryInfo;
    }

    /**
     * 将Date转换为LocalDateTime
     */
    private LocalDateTime convertToLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
